package com.flyqiu.form.spring.boot.starter;

import com.flyqiu.common.tools.FlyQiuCollectionTools;
import com.flyqiu.form.api.col.FlyQiuStoreColTypeManage;
import com.flyqiu.form.api.spi.FlyQiuFormStoreInitialization;
import com.flyqiu.form.api.store.FlyQiuFormStoreManage;
import com.flyqiu.form.api.store.FlyQiuFormStoreService;
import com.flyqiu.form.core.BaseFlyQiuForm;
import org.springframework.beans.factory.InitializingBean;

import java.util.List;

/**
 * Spring环境下的FlyQiu表单实现类。
 */
public class SpringFlyQiuFormImpl extends BaseFlyQiuForm implements InitializingBean {

    private final SpringFlyQiuFormConfig flyQiuFormConfig;

    /**
     * 构造函数，初始化上下文和配置。
     *
     * @param flyQiuFormContext 上下文
     * @param flyQiuFormConfig  配置
     */
    public SpringFlyQiuFormImpl(SpringFlyQiuFormContext flyQiuFormContext, SpringFlyQiuFormConfig flyQiuFormConfig) {
        this.context = flyQiuFormContext;
        this.flyQiuFormConfig = flyQiuFormConfig;
    }

    /**
     * 在所有属性设置完成后调用此方法。
     * 初始化表单配置。
     *
     * @throws Exception 异常
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        init(flyQiuFormConfig);
    }

    /**
     * 加载存储列类型。
     *
     * @param flyQiuStoreColTypeManage 存储列类型管理器
     */
    @Override
    protected void loadFlyQiuStoreColType(FlyQiuStoreColTypeManage flyQiuStoreColTypeManage) {
        List<FlyQiuFormStoreInitialization> initializations = flyQiuFormConfig.getFlyQiuFormStoreInitializations();
        FlyQiuCollectionTools.iterator(initializations, flyQiuStoreColTypeManage::registerStoreColType);
    }

    /**
     * 加载表单存储服务。
     *
     * @param formStoreManage 表单存储管理器
     */
    @Override
    protected void loadFormStores(FlyQiuFormStoreManage formStoreManage) {
        List<FlyQiuFormStoreInitialization> initializations = flyQiuFormConfig.getFlyQiuFormStoreInitializations();
        FlyQiuCollectionTools.iterator(initializations, flyQiuFormStoreInitialization -> {
            FlyQiuFormStoreService storeService = flyQiuFormStoreInitialization.initFormStore(context);
            formStoreManage.registerStore(storeService);
        });
    }
}
